package com.springmvc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class FileDownController {
    /**
     * 显示要下载的文件
     */
    @RequestMapping("/showDownFiles")
    public String show(HttpServletRequest request, Model model) {
        String realpath = "c:/aServer/";
        File dir = new File(realpath);
        File files[] = dir.listFiles();
        // 获取该目录下的所有文件名
        ArrayList<String> fileName = new ArrayList<String>();
        for (int i = 0; i < files.length; i++) {
            fileName.add(files[i].getName());
        }
        model.addAttribute("files", fileName);
        return "showDownFiles";
    }

    /**
     * 执行下载
     */
    @RequestMapping("/down")
    public void down(@RequestParam String filename,
                       HttpServletRequest request, HttpServletResponse response) throws IOException {
        FileInputStream in = null; // 输入流
        ServletOutputStream out = null; // 输出流
        String realpath = "c:/aServer/";
        // 设置下载文件使用的报头
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        // 读入文件
        in = new FileInputStream(realpath + "\\" + filename);
        // 得到响应对象的输出流，用于向客户端输出二进制数据
        out = response.getOutputStream();

        int aRead = 0;
        byte b[] = new byte[1024];
        while ((aRead = in.read(b)) != -1 & in != null) {
            out.write(b, 0, aRead);
        }
        out.flush();
        in.close();
        out.close();
    }
}

